package bingosoft.metro.datasync.base.service;

import bingosoft.metro.datasync.base.model.SyncModel;
import leap.lang.Strings;
import leap.orm.model.Model;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Feily
 * @功能描述 增量同步数据服务基础类
 * @创建时间 2017-12-13
 */
public abstract class IncSyncService extends FullSyncService{

	/**
	 * 获取最后更新时间SQL
	 */
	protected String getLastSyncTimeSql;
	
	/**
	 * 构建函数
	 */
	public IncSyncService() {
		this.setLogClass(this.getClass());
	}

	@Override
	public List<Model> getSyncDataList() {
		
		// 获取最后更新时间
		Date lastSyncTime = this.getLastSyncTime();
	
		// 获取同步数据信息列表
		List<Model> syncData = this.getSyncDataList(lastSyncTime);
		return syncData;
	}
	
	/**
	 * 获取最后更新时间
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public Date getLastSyncTime() {
		this.logMethodCalled("getLastSyncTime");
		
		if(Strings.isEmpty(this.getLastSyncTimeSql)){
			throw new RuntimeException("属性【getLastSyncTimeSql】不能为空");
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tenantCode", this.tenantCode);
	
		SyncModel syncModel = SyncModel.<SyncModel>query(this.getLastSyncTimeSql).params(params).firstOrNull();
		if(syncModel != null){
			return syncModel.getLastSyncTime();
		}else{
			int year = 10;
			this.logMessage(Strings.format("最后更新时间为空，默认使用{0}年前时间", year));
			
			Date date = new Date();
			date.setYear(date.getYear() - 10);
			return date;
		}
	}
	
	/**
	 * 获取同步数据信息列表
	 * @param lastSyncTime
	 * @return
	 */
	public abstract List<Model> getSyncDataList(Date lastSyncTime);
}
